package ricardotavares.util.som;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;

/**
 *
 * @author Ricardo
 */
public class Audio extends Thread {

    private Clip clip;
    private AudioInputStream stream1;
    private AudioFormat format;
    private DataLine.Info info;

    public Audio(String url) {
        try {
            stream1 = AudioSystem.getAudioInputStream(new File(url));
            format = stream1.getFormat();

            if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true);        // big endian
                stream1 = AudioSystem.getAudioInputStream(format, stream1);
            }

            info = new DataLine.Info(Clip.class, stream1.getFormat(), ((int) stream1.getFrameLength() * format.getFrameSize()));
            clip = (Clip) AudioSystem.getLine(info);
            clip.open(stream1);
        } catch (UnsupportedAudioFileException ex) {
            JOptionPane.showMessageDialog(null, "1 - ERRO: " + ex);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "2 - ERRO: " + ex);
        } catch (LineUnavailableException ex) {
            JOptionPane.showMessageDialog(null, "3 - ERRO CLIP: " + ex);
        }
    }

    public void run() {
        clip.start();

        while (clip.isOpen()) {
            try {
                join(2000);

                if (!clip.isRunning()) {
                    destroy();
                }
            } catch (InterruptedException ex) {
                System.out.println("Erro ao tocar o som: " + ex);
            }
        }
    }

    public void stopAudio(){
        clip.stop();
    }

    public Clip getAudio(){
        return clip;
    }

    public static void main(String args[]) {
        Audio music = new Audio("d:/bumbum.wav");
        music.start();
    }
}
